// 六通道遥控发射端 arduino nano + NRF24L01 + st7735

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>


// ST7735显示屏引脚
#define TFT_DC 2
#define TFT_CS 4
#define TFT_RES 7

// NRF无线模块引脚
#define NRF_CE 9
#define NRF_CSN 10


unsigned long lastDisplayTime = 0; // 上次屏幕刷新数据的时间
unsigned long lastRecAckTime = 0; // 上次收到自动应答数据的时间
const uint64_t pipeOut = 0xE9E8F0F0E1LL;   // 无线通讯密钥
RF24 radio(NRF_CE, NRF_CSN); // 初始化RF24库
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RES); // 初始化tft库



struct Signal {
  byte throttle;
  byte pitch;
  byte roll;
  byte yaw;
  byte aux1;
  bool aux2;
};


float battery;  //受控端电池电压  



Signal data;

void ResetData() {
  data.throttle = 127;
  data.pitch = 127;   
  data.roll = 127;    
  data.yaw = 127;   
  data.aux1 = 127;   
  data.aux2 = 0;   
}


void setup(){
//  Serial.begin(9600);
  pinMode(8,INPUT_PULLUP);
  //初始化RF24通讯
  radio.begin();
  radio.openWritingPipe(pipeOut);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.setPayloadSize(32);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);
  radio.stopListening(); //设置为发射模式

  //初始化ST7735
  tft.initR(INITR_BLACKTAB); // 初始化显示屏
  tft.setRotation(3);
  tft.fillScreen(ST7735_BLACK); //清屏
  tft.setTextColor(ST7735_WHITE); // 设置文字颜色
  tft.setTextSize(1); // 设置文本大小
  ResetData();
}


int mapJoystickValues(int val, int lower, int middle, int upper, bool reverse){
  val = constrain(val, lower, upper);
  if ( val < middle ){
    val = map(val, lower, middle, 0, 128);
  }else{
    val = map(val, middle, upper, 128, 255);
  }
  return ( reverse ? 255 - val : val );
}


void loop(){
  data.throttle = mapJoystickValues( analogRead(A1), 12, 524, 1020, true );  
  data.roll = mapJoystickValues( analogRead(A3), 12, 524, 1020, true );     
  data.pitch = mapJoystickValues( analogRead(A2), 12, 524, 1020, false );     
  data.yaw = mapJoystickValues( analogRead(A0), 12, 524, 1020, false );       
  data.aux1 = mapJoystickValues( analogRead(A6), 12, 524, 1020, true );     
  data.aux2 = digitalRead(8);     
  radio.write(&data, sizeof(Signal));
  if (radio.isAckPayloadAvailable()){
    lastRecAckTime = millis(); 
    int rec_val;
    radio.read(&rec_val, sizeof(rec_val));
    battery = rec_val / 100.0;
  }

  if (millis() - lastDisplayTime > 1000){
    lastDisplayTime = millis();
    displayData();
  }  
}

void displayData(){
  tft.fillScreen(ST7735_BLACK); //清屏
  tft.setCursor(0,30);
  tft.print(" Throttle: "); tft.println(data.throttle);
  tft.print(" roll: "); tft.println(data.roll);
  tft.print(" pitch: "); tft.println(data.pitch);
  tft.print(" yaw: "); tft.println(data.yaw);
  tft.print(" aux1: "); tft.println(data.aux1);
  tft.print(" aux2: "); tft.println(data.aux2);
  tft.print(" recTime:"); tft.print((millis()-lastRecAckTime)/1000); tft.print("s: "); tft.print(battery);tft.println("v");
}
